package com.funo.wcity.app.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.funo.wcity.app.entity.LoginUser;
import com.funo.wcity.app.entity.TblContactPersons;
import com.funo.wcity.app.entity.TblMailAnnex;
import com.funo.wcity.app.entity.TblMailDetail;
import com.funo.wcity.app.entity.TblUserMail;
import com.funo.wcity.app.entity.TblUsers;
import com.funo.wcity.app.service.TblCompaniesService;
import com.funo.wcity.app.service.TblCompanyTypesService;
import com.funo.wcity.app.service.TblContactPersonsService;
import com.funo.wcity.app.service.TblMailAnnexService;
import com.funo.wcity.app.service.TblMailDetailService;
import com.funo.wcity.app.service.TblUserMailService;
import com.funo.wcity.app.service.TblUsersService;
import com.funo.wcity.app.service.mail.send.MailBean;
import com.funo.wcity.app.service.mail.send.MailConstant;
import com.funo.wcity.app.service.mail.send.MailSender;
import com.funo.wcity.app.utils.Base64Util;
import com.funo.wcity.app.utils.CacheUtil;
import com.funo.wcity.app.utils.Constant;
import com.funo.wcity.app.utils.JsonUtil;
import com.funo.wcity.app.utils.PubFile;
import com.funo.wcity.app.utils.StringUtil;

@Controller
@SuppressWarnings("all")
public class SendMailController extends CommonController{
	private static  Log log=LogFactory.getLog(SendMailController.class); //日志
	@Resource(name="tblMailDetailService")
	private TblMailDetailService tblMailDetailService;	
	@Resource(name="tblMailAnnexService")
	private TblMailAnnexService tblMailAnnexService;
	@Resource(name="tblContactPersonsService")
	private TblContactPersonsService tblContactPersonsService;
	@Resource(name="tblCompaniesService")
	private TblCompaniesService tblCompaniesService;
	@Resource(name="tblCompanyTypesService")
	private TblCompanyTypesService tblCompanyTypesService;
	@Resource(name="tblUserMailService")
	private TblUserMailService tblUserMailService;
	@Resource(name="tblUsersService")
	private TblUsersService  tblUsersService;
	
	/**
	 * 发送电子邮件
	 */
	@RequestMapping("/sendEmail")
	public String sendEmail(HttpServletRequest request,HttpServletResponse response,MailBean mailBean,TblMailDetail tblMailDetail,Integer idUserMail){
		//查询当前人员信息
		LoginUser loginUser=(LoginUser)request.getSession().getAttribute(Constant.LOGIN_USER);
		//查询email账号信息
		TblUserMail tblUserMail=this.tblUserMailService.getTblUserMail(idUserMail);
		try{
			//解密
			tblUserMail.setPassword(new String(Base64Util.decode(tblUserMail.getPassword())));
			String tempContent=mailBean.getContent();
			//设置邮件信息
			mailBean = setMailBean(request,mailBean,tblMailDetail,tblUserMail);
			//收件人
			if(!StringUtil.isEmpty(mailBean.getToAddress())){
				mailBean.setToAddress(mailBean.getToAddress().replaceAll(";", ","));
			}
			//抄送人
			if(!StringUtil.isEmpty(mailBean.getToCc())){
				mailBean.setToCc(mailBean.getToCc().replaceAll(";", ","));
			}
			//密送人
			if(!StringUtil.isEmpty(mailBean.getToBcc())){
				mailBean.setToBcc(mailBean.getToBcc().replaceAll(";", ","));
			}
			mailBean.setFromAddress(tblUserMail.getEmail());
			mailBean.setUserName(tblUserMail.getEmail());
			mailBean.setPassword(tblUserMail.getPassword());
			mailBean.setPop(tblUserMail.getPop());
			mailBean.setSmtp(tblUserMail.getSmtp());
			mailBean.setImap(tblUserMail.getImap());
			mailBean.setMailDate(new Date());
			mailBean.setValidate(true);
			//发送邮件
			MailSender mailSender=new MailSender(mailBean);
			boolean rtnBoolean=mailSender.sendMail();
			if(rtnBoolean){
				//将文件保存到本地数据库
				tblMailDetail.setIdUser(loginUser.getIdUser());
				tblMailDetail.setCopySend(mailBean.getToCc());
				tblMailDetail.setSecretSend(mailBean.getToBcc());
				tblMailDetail.setRecPeople(mailBean.getToAddress());
				tblMailDetail.setSendPeople(tblUserMail.getEmail());
				tblMailDetail.setTitle(mailBean.getSubject());
				tblMailDetail.setContent(tempContent);
				tblMailDetail.setState(MailConstant.SENDED);
				tblMailDetail.setLastDate(new Date());
				//1已读标志，0未读标志
				tblMailDetail.setMailSign(0);
				//公司类型id，公司id，联系人id
				String idCompanyType="",idCompany="",idContactPerson="";
				//收件人信息
				if(!StringUtil.isEmpty(StringUtil.reTrimByString(tblMailDetail.getRecPeople()))){
					String[] toAttr=mailBean.getToAddress().replaceAll(" ", "").split("\\,");
					for(int j=0;j<toAttr.length;j++){
						if(toAttr[j].indexOf("<")>-1){
							toAttr[j]=toAttr[j].substring(toAttr[j].indexOf("<")+1, toAttr[j].indexOf(">"));
						}
						TblContactPersons tblContactPersons=this.tblContactPersonsService.getTblContactPersons(toAttr[j]);
						if(tblContactPersons!=null){
							if(StringUtil.isEmpty(idCompanyType))idCompanyType=",";
							if(StringUtil.isEmpty(idCompany))idCompany=",";
							if(StringUtil.isEmpty(idContactPerson))idContactPerson=",";
							if(idContactPerson.indexOf(","+tblContactPersons.getIdContactPerson()+",")==-1){
								idContactPerson+=tblContactPersons.getIdContactPerson()+",";
							}
							if(idCompany.indexOf(","+tblContactPersons.getTblcompanies().getIdCompany()+",")==-1){
								idCompany+=tblContactPersons.getTblcompanies().getIdCompany()+",";
							}
							if(idCompanyType.indexOf(","+tblContactPersons.getTblcompanies().getIdCompanyType()+",")==-1){
								idCompanyType+=tblContactPersons.getTblcompanies().getIdCompanyType()+",";
							}
						}
					}
				}
				tblMailDetail.setIdCompanyType(idCompanyType);
				tblMailDetail.setIdCompany(idCompany);
				tblMailDetail.setIdContactPerson(idContactPerson);
				this.tblMailDetailService.saveMailDetail(tblMailDetail);
				//返回成功响应信息
				JsonUtil.stringPrintJson(request, response, "true");
			}else{
				JsonUtil.stringPrintJson(request, response, "false");
			}
		}catch(Exception e){
			log.error("发送电子邮件失败，原因是："+e.getMessage(),e);
			JsonUtil.stringPrintJson(request, response, "false");
		}
		return null;
	}
	/**
	 * 保存到草稿箱
	 */
	@RequestMapping("/saveDraft")
	public String saveDraft(HttpServletRequest request,HttpServletResponse response,MailBean mailBean,TblMailDetail tblMailDetail,Integer idUserMail) {
		try {
			//查询当前人员信息
			LoginUser loginUser=(LoginUser)request.getSession().getAttribute(Constant.LOGIN_USER);
			//查询email账号信息
			TblUserMail tblUserMail=this.tblUserMailService.getTblUserMail(idUserMail);
			//将文件保存到本地数据库
			tblMailDetail.setIdUser(loginUser.getIdUser());
			tblMailDetail.setCopySend(mailBean.getToCc());
			tblMailDetail.setSecretSend(mailBean.getToBcc());
			tblMailDetail.setRecPeople(mailBean.getToAddress());
			tblMailDetail.setSendPeople(tblUserMail.getEmail());
			tblMailDetail.setTitle(mailBean.getSubject());
			tblMailDetail.setContent(mailBean.getContent());
			tblMailDetail.setState(MailConstant.DRAFT);
			tblMailDetail.setLastDate(new Date());
			//1已读标志，0未读标志
			tblMailDetail.setMailSign(0);
			//收件人
			if(!StringUtil.isEmpty(mailBean.getToAddress())){
				tblMailDetail.setRecPeople(mailBean.getToAddress().replaceAll(";", ","));
			}
			//抄送人
			if(!StringUtil.isEmpty(mailBean.getToCc())){
				tblMailDetail.setCopySend(mailBean.getToCc().replaceAll(";", ","));
			}
			//密送人
			if(!StringUtil.isEmpty(mailBean.getToBcc())){
				tblMailDetail.setSecretSend(mailBean.getToBcc().replaceAll(";", ","));
			}
			//公司类型id，公司id，联系人id
			String idCompanyType="",idCompany="",idContactPerson="";
			//拆分发件人
			String from =tblMailDetail.getSendPeople();
			if(!StringUtil.isEmpty(from)){
				if(from.indexOf("<")>-1){
					from=from.substring(from.indexOf("<")+1, from.indexOf(">"));
				}
			}
			//通过发件人邮箱查询联系人信息
			TblContactPersons tblContactPersons=this.tblContactPersonsService.getTblContactPersons(from);
			if(tblContactPersons!=null){
				idCompanyType=",";idCompany=",";idContactPerson=",";
				idContactPerson+=tblContactPersons.getIdContactPerson()+",";
				idCompany+=tblContactPersons.getTblcompanies().getIdCompany()+",";
				idCompanyType+=tblContactPersons.getTblcompanies().getIdCompanyType()+",";
			}
			//收件人信息
			if(!StringUtil.isEmpty(StringUtil.reTrimByString(tblMailDetail.getRecPeople()))){
				String[] toAttr=mailBean.getToAddress().replaceAll(" ", "").split("\\,");
				for(int j=0;j<toAttr.length;j++){
					if(toAttr[j].indexOf("<")>-1){
						toAttr[j]=toAttr[j].substring(toAttr[j].indexOf("<")+1, toAttr[j].indexOf(">"));
					}
					tblContactPersons=this.tblContactPersonsService.getTblContactPersons(toAttr[j]);
					if(tblContactPersons!=null){
						if(StringUtil.isEmpty(idCompanyType))idCompanyType=",";
						if(StringUtil.isEmpty(idCompany))idCompany=",";
						if(StringUtil.isEmpty(idContactPerson))idContactPerson=",";
						if(idContactPerson.indexOf(","+tblContactPersons.getIdContactPerson()+",")==-1){
							idContactPerson+=tblContactPersons.getIdContactPerson()+",";
						}
						if(idCompany.indexOf(","+tblContactPersons.getTblcompanies().getIdCompany()+",")==-1){
							idCompany+=tblContactPersons.getTblcompanies().getIdCompany()+",";
						}
						if(idCompanyType.indexOf(","+tblContactPersons.getTblcompanies().getIdCompanyType()+",")==-1){
							idCompanyType+=tblContactPersons.getTblcompanies().getIdCompanyType()+",";
						}
					}
				}
			}
			tblMailDetail.setIdCompanyType(idCompanyType);
			tblMailDetail.setIdCompany(idCompany);
			tblMailDetail.setIdContactPerson(idContactPerson);
			this.tblMailDetailService.saveMailDetail(tblMailDetail);
			//返回成功响应信息
			JsonUtil.stringPrintJson(request, response, "true");
		} catch (Exception e) {
			log.error("保存到草稿箱失败，原因是："+e.getMessage(),e);
			JsonUtil.stringPrintJson(request, response, "false");
		}
		return null;
	}
	/**
	 * 写信
	 */
	@RequestMapping("/writeEmail")
	public String writeEmail(HttpServletRequest request,HttpServletResponse response, Long idMailDetail) {
		try{
			//查询当前人员信息
			LoginUser loginUser = (LoginUser) request.getSession().getAttribute(Constant.LOGIN_USER);
			TblMailDetail tblMailDetail = null;
			if (!StringUtil.isEmpty(idMailDetail)) {
				// 查询邮件明细
				tblMailDetail = this.tblMailDetailService.getTblMailDetail(idMailDetail);
				// 收件人
				if (!StringUtil.isEmpty(tblMailDetail.getRecPeople())) {
					tblMailDetail.setRecPeople(tblMailDetail.getRecPeople().replaceAll(",", ";"));
				}
				// 抄送人
				if (!StringUtil.isEmpty(tblMailDetail.getCopySend())) {
					tblMailDetail.setCopySend(tblMailDetail.getCopySend().replaceAll(",", ";"));
				}
				// 密送人
				if (!StringUtil.isEmpty(tblMailDetail.getSecretSend())) {
					tblMailDetail.setSecretSend(tblMailDetail.getSecretSend().replaceAll(",", ";"));
				}
				// 查询附件列表
				List mailAnnexList = this.tblMailAnnexService.getTblMailAnnexList(
						tblMailDetail.getIdMailAnnex(), 1);
				request.setAttribute("mailAnnexList", mailAnnexList);
			} else {
				tblMailDetail = new TblMailDetail();
			}
			// 查询当前用户
			TblUsers tblUsers = this.tblUsersService.getTblUsers(loginUser.getIdUser());
			if(!StringUtil.isEmpty(tblMailDetail.getContent())){
				tblMailDetail.setContent((tblMailDetail.getContent()==null?"":tblMailDetail.getContent()));
			}
			request.setAttribute("tblMailDetail", tblMailDetail);
			String idEmployees =(String)request.getSession().getAttribute(Constant.LOGIN_EMPLOYEE);
			// 查询所有公司类型
			List tblCompanyTypesList = this.tblCompanyTypesService.getTblCompanyTypesList(idEmployees);
			request.setAttribute("tblCompanyTypesList", tblCompanyTypesList);
			// 查询帐号邮箱列表
			List userMailList=this.tblUserMailService.getTblUserMailList(loginUser.getIdUser());
			request.setAttribute("userMailList",userMailList);
			//获取默认邮箱
			request.setAttribute("defEmail",CacheUtil.defMail);
		}catch(Exception e){
			log.error("写信失败，原因是："+e.getMessage(),e);
			return "web/opera_fail";
		}
		return "web/send_index";
	}
	/**
	 * 回复
	 */
	@RequestMapping("/reply")
	public String  reply(HttpServletRequest request,HttpServletResponse response,Long idMailDetail){
		try{
			//查询当前人员信息
			LoginUser loginUser=(LoginUser)request.getSession().getAttribute(Constant.LOGIN_USER);
			//查询邮件明细
			TblMailDetail tblMailDetail=this.tblMailDetailService.getTblMailDetail(idMailDetail);
			StringBuffer content = new StringBuffer();
			SimpleDateFormat f=new SimpleDateFormat("yyyy年MM月dd日 E HH点mm分");
			content.append("<br/>").append("<br/>").append("<br/>")
			.append("<div 0px;color:#000000;text-transform:none;text-indent:0px;letter-spacing:normal;word-spacing:0px;white-space:normal;orphans:2;widows:2;font-size-adjust:none;font-stretch:normal;background-color:#FFFFFF;-webkit-text-size-adjust:auto;-webkit-text-stroke-width:0px;?=\"\" Narrow?;padding:2px=\"\" Arial=\"\">")
			.append("------------------&nbsp;原始邮件&nbsp;------------------")
			.append("</div>")
			.append("<div style=\"font:12px/1.5 Verdana;padding:8px;color:#000000;text-transform:none;text-indent:0px;letter-spacing:normal;word-spacing:0px;white-space:normal;orphans:2;widows:2;font-size-adjust:none;font-stretch:normal;background-color:#EFEFEF;-webkit-text-size-adjust:auto;-webkit-text-stroke-width:0px;\">")
			.append("<div style=\"line-height:1.5;\">")
			.append("<b>发件人:</b> ").append(tblMailDetail.getSendPeople()).append(";")
			.append("</div>")
			.append("<div style=\"line-height:1.5;\">")
			.append("<b>发送时间:</b> ").append(f.format(tblMailDetail.getLastDate()))
			.append("</div>")
			.append("<div style=\"line-height:1.5;\">")
			.append("<b>收件人:</b>").append(tblMailDetail.getRecPeople()).append(";")
			.append("</div>")
			.append("<div style=\"line-height:1.5;\">")
			.append("<b>主题:</b> ").append(tblMailDetail.getTitle())
			.append("</div>")
			.append("</div>")
			.append("<br/>");
			tblMailDetail.setContent(content.toString() + tblMailDetail.getContent());
			//收件人
			tblMailDetail.setRecPeople(tblMailDetail.getSendPeople());
			if(!StringUtil.isEmpty(tblMailDetail.getRecPeople())){
				tblMailDetail.setRecPeople(tblMailDetail.getRecPeople().replaceAll(" ", "").replaceAll(",", ";").replaceAll("\t", ""));
			}
			//抄送人
			tblMailDetail.setCopySend("");
			//密送人
			tblMailDetail.setSecretSend("");
			request.setAttribute("tblMailDetail", tblMailDetail);
			//查询附件列表
			List mailAnnexList=this.tblMailAnnexService.getTblMailAnnexList(tblMailDetail.getIdMailAnnex(),1);
			request.setAttribute("mailAnnexList", mailAnnexList);
			String idEmployees=(String)request.getSession().getAttribute(Constant.LOGIN_EMPLOYEE);
			//查询所有公司类型
			List tblCompanyTypesList=this.tblCompanyTypesService.getTblCompanyTypesList(idEmployees);
			request.setAttribute("tblCompanyTypesList", tblCompanyTypesList);
			//查询帐号邮箱列表
			request.setAttribute("userMailList",this.tblUserMailService.getTblUserMailList(loginUser.getIdUser()));
		}catch(Exception e){
			log.error("回复失败，原因是："+e.getMessage(),e);
			return "web/opera_fail";
		}
		return "web/send_index";
	}
	/**
	 * 回复全部
	 */
	@RequestMapping("/replyAll")
	public String  replyAll(HttpServletRequest request,HttpServletResponse responsem,Long idMailDetail){
		try{
			LoginUser loginUser=(LoginUser)request.getSession().getAttribute(Constant.LOGIN_USER);
			//查询邮件明细
			TblMailDetail tblMailDetail=this.tblMailDetailService.getTblMailDetail(idMailDetail);
			StringBuffer content = new StringBuffer();
			SimpleDateFormat f=new SimpleDateFormat("yyyy年MM月dd日 E HH点mm分");
			content.append("<br/>").append("<br/>").append("<br/>")
			.append("<div 0px;color:#000000;text-transform:none;text-indent:0px;letter-spacing:normal;word-spacing:0px;white-space:normal;orphans:2;widows:2;font-size-adjust:none;font-stretch:normal;background-color:#FFFFFF;-webkit-text-size-adjust:auto;-webkit-text-stroke-width:0px;?=\"\" Narrow?;padding:2px=\"\" Arial=\"\">")
			.append("------------------&nbsp;原始邮件&nbsp;------------------")
			.append("</div>")
			.append("<div style=\"font:12px/1.5 Verdana;padding:8px;color:#000000;text-transform:none;text-indent:0px;letter-spacing:normal;word-spacing:0px;white-space:normal;orphans:2;widows:2;font-size-adjust:none;font-stretch:normal;background-color:#EFEFEF;-webkit-text-size-adjust:auto;-webkit-text-stroke-width:0px;\">")
			.append("<div style=\"line-height:1.5;\">")
			.append("<b>发件人:</b> ").append(tblMailDetail.getSendPeople()).append(";")
			.append("</div>")
			.append("<div style=\"line-height:1.5;\">")
			.append("<b>发送时间:</b> ").append(f.format(tblMailDetail.getLastDate()))
			.append("</div>")
			.append("<div style=\"line-height:1.5;\">")
			.append("<b>收件人:</b> ").append(tblMailDetail.getRecPeople()).append(";")
			.append("</div>")
			.append("<div style=\"line-height:1.5;\">")
			.append("<b>主题:</b> ").append(tblMailDetail.getTitle())
			.append("</div>")
			.append("</div>")
			.append("<br/>");
			tblMailDetail.setContent(content.toString() + tblMailDetail.getContent());
			//抄送人
			if(StringUtil.isEmpty(tblMailDetail.getCopySend())){
				tblMailDetail.setCopySend(tblMailDetail.getRecPeople());
			}else{
				tblMailDetail.setCopySend(tblMailDetail.getRecPeople()+";"+tblMailDetail.getCopySend());
			}
			if(!StringUtil.isEmpty(tblMailDetail.getCopySend())){
				tblMailDetail.setCopySend(tblMailDetail.getCopySend().replaceAll(" ", "").replaceAll(",", ";").replaceAll("\t", ""));
			}
			//收件人
			tblMailDetail.setRecPeople(tblMailDetail.getSendPeople());
			if(!StringUtil.isEmpty(tblMailDetail.getRecPeople())){
				tblMailDetail.setRecPeople(tblMailDetail.getRecPeople().replaceAll(" ", "").replaceAll(",", ";").replaceAll("\t", ""));
			}
			//密送人
			if(!StringUtil.isEmpty(tblMailDetail.getSecretSend())){
				tblMailDetail.setSecretSend(tblMailDetail.getSecretSend().replaceAll(" ", "").replaceAll(",", ";").replaceAll("\t", ""));
			}
			request.setAttribute("tblMailDetail", tblMailDetail);
			//查询附件列表
			List mailAnnexList=this.tblMailAnnexService.getTblMailAnnexList(tblMailDetail.getIdMailAnnex(),1);
			request.setAttribute("mailAnnexList", mailAnnexList);
			String idEmployees=(String)request.getSession().getAttribute(Constant.LOGIN_EMPLOYEE);
			//查询所有公司类型
			List tblCompanyTypesList=this.tblCompanyTypesService.getTblCompanyTypesList(idEmployees);
			request.setAttribute("tblCompanyTypesList", tblCompanyTypesList);
			//查询帐号邮箱列表
			request.setAttribute("userMailList",this.tblUserMailService.getTblUserMailList(loginUser.getIdUser()));
		}catch(Exception e){
			log.error("回复全部失败，原因是："+e.getMessage(),e);
			return "web/opera_fail";
		}
		return "web/send_index";
	}
	/**
	 * 发送成功提示
	 */
	@RequestMapping("/sendSuccess")
	public String sendSuccess(HttpServletRequest request,HttpServletResponse response){
		return "web/send_success";
	}
	/******************************************************
	 ***********************JQUERY相关**********************
	 ******************************************************/
	/**
	 * 删除硬盘中的附件信息
	 */
	@RequestMapping("/deleteAttachmentJQ")
	private String deleteAttachmentJQ(HttpServletRequest request,HttpServletResponse response,Integer idMailAnnex,Long idMailDetail) {
		try{
			String path = request.getSession().getServletContext().getRealPath("")+ Constant.PATH;
			//邮件附件对象
			TblMailAnnex tblMailAnnex=this.tblMailAnnexService.getTblMailAnnex(idMailAnnex);
			//邮件明细对象
			if(!StringUtil.isEmpty(idMailDetail)){
				TblMailDetail tblMailDetail=this.tblMailDetailService.getTblMailDetail(idMailDetail);
				if(tblMailDetail!=null){
					if(!StringUtil.isEmpty(tblMailDetail.getIdMailAnnex())){
						String[] idMailAnnexAttr=tblMailDetail.getIdMailAnnex().split("\\,");
						StringBuffer sb=new StringBuffer();
						for(int i=0;i<idMailAnnexAttr.length;i++){
							if(!String.valueOf(idMailAnnex).equals(idMailAnnexAttr[i])){
								sb.append(idMailAnnexAttr[i]).append(",");
							}
						}
						String temp=sb.substring(0, sb.length()-1);
						tblMailDetail.setIdMailAnnex(temp);
						//修改邮件表里关联邮件明细id
						this.tblMailDetailService.saveMailDetail(tblMailDetail);
					}
				}
			}
			//删除文件操作
			String fileName=tblMailAnnex.getFilename();
			String folder=fileName.substring(0, fileName.indexOf("/")+1);
			File file=new File(path+folder);
			PubFile pubFile=new PubFile();
			pubFile.deleteFilefolder(file);
			//删除附件
			this.tblMailAnnexService.delTblMailAnnex(tblMailAnnex);
			JsonUtil.stringPrintJson(request, response, "true");
		}catch(Exception e){
			log.error("删除硬盘中的附件信息失败，原因是："+e.getMessage(),e);
			JsonUtil.stringPrintJson(request, response, "false");
		}
		return null;
	}
	/**
	 * 上传附件
	 */
	@RequestMapping("/uploadFile")
    public String uploadFileJq(HttpServletRequest request,HttpServletResponse response) {
		try {
			String savePath =request.getSession().getServletContext().getRealPath("/")+Constant.PATH;
			//创建磁盘文件工厂
			DiskFileItemFactory fac = new DiskFileItemFactory();    
			//创建servlet文件上传组件
			ServletFileUpload upload = new ServletFileUpload(fac);      
			//解析request从而得到前台传过来的文件 
			List fileList = upload.parseRequest(request);    
			//便利从前台得到的文件列表
			Iterator<FileItem> it = fileList.iterator();
			String fileName=System.currentTimeMillis()+"/";
			while(it.hasNext()){    
			    FileItem item =  it.next();   
			    //如果不是普通表单域，当做文件域来处理
			    if(!item.isFormField()){
			    	PubFile pubFile=new PubFile(savePath+fileName);
			    	//判断文件夹是否存在
			    	if(!pubFile.isExists()){
			    		pubFile.createFilefolder();
			    	}
			    	fileName=fileName+item.getName();
			    	BufferedInputStream in = new BufferedInputStream(item.getInputStream());
			        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(savePath+fileName)));
			        Streams.copy(in, out, true);
			        //保存附件数据
			        TblMailAnnex tblMailAnnex=new TblMailAnnex();
			        tblMailAnnex.setFilename(fileName);
			        //1 附件，2嵌入附件
			        tblMailAnnex.setStatus(1);
			        tblMailAnnex.setLastDate(new Date());
			        this.tblMailAnnexService.saveTblMailAnnex(tblMailAnnex);
			        //返回上传文件信息
			        String msg=tblMailAnnex.getIdMailAnnex()+";"+item.getName();
					JsonUtil.stringPrintJson(request, response,msg);
					return null;
			    }
			}
		} catch (Exception e) {
			log.error("上传附件失败，原因是："+e.getMessage(),e);
			JsonUtil.stringPrintJson(request, response, "0");
		}
		JsonUtil.stringPrintJson(request, response, "0");
		return null;
	}		
	/**
	 * 查询写信联系人（格式：公司名称->联系人）
	 */
	@RequestMapping("/queryWritePerson")
	public String queryWritePerson(HttpServletRequest request,HttpServletResponse response,Integer idCompanyType){
		try{
			List dataList=new ArrayList();
			String loginEmployee=(String)request.getSession().getAttribute(Constant.LOGIN_EMPLOYEE);
			//查询所有公司
			List companiesList=this.tblCompaniesService.getTblCompaniesList(loginEmployee, idCompanyType);
			//查询联系人
			List contactPersonsList=this.tblContactPersonsService.getContactPersonslList(loginEmployee, idCompanyType);
			//构造_公司名称->联系人
			StringBuffer parent=new StringBuffer();
			for(int i=0;i<companiesList.size();i++){
				Map obj=(Map)companiesList.get(i);
				parent.append("<div id=\"type_"+i+"\"><a href='JavaScript:showOrHide("+i+")'>&nbsp;&nbsp;&nbsp;&nbsp;").append(obj.get("COMPANYNAME")).append("</a></div>");
				parent.append("<div id=\"content_"+i+"\" style=\"display:none\">");
				StringBuffer sub=new StringBuffer();
				for(int j=0;j<contactPersonsList.size();j++){
					Map obj2=(Map)contactPersonsList.get(j);
					if(obj.get("IDCOMPANY").equals(obj2.get("IDCOMPANY"))){
						sub.append("<li><a href='JavaScript:focuUser(\""+obj.get("IDCOMPANY")+"\",\""+obj2.get("IDCONTACTPERSON")+"\",\""+obj2.get("EMAIL")+"\",\""+obj2.get("FIRSTNAME")+obj2.get("LASTNAME")+"\")' title=\""+obj2.get("EMAIL")+"\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;").append(obj2.get("FIRSTNAME")).append(obj2.get("LASTNAME")).append("</a></li>");
					}
				}
				if(sub.length()>0){
					parent.append("<ul>");
					parent.append(sub.toString());
					parent.append("</ul>");	
				}
				parent.append("</div>");
			}
			JsonUtil.stringPrintJson(request, response,parent.toString());
		}catch(Exception e){
			log.error("查询联系人失败，原因是："+e.getMessage(),e);
			JsonUtil.stringPrintJson(request, response, "false");
		}
		return null;
	}
	/**
	 * 查询_收件箱/草稿箱/已发送/已删除/垃圾箱联系人（格式：公司名称->联系人）
	 */
	@RequestMapping("/queryCommPerson")
	public String queryCommPerson(HttpServletRequest request,HttpServletResponse response,Integer idCompanyType){
		try{
			List dataList=new ArrayList();
			String loginEmployee=(String)request.getSession().getAttribute(Constant.LOGIN_EMPLOYEE);
			//查询所有公司
			List companiesList=this.tblCompaniesService.getTblCompaniesList(loginEmployee, idCompanyType);
			//查询联系人
			List contactPersonsList=this.tblContactPersonsService.getContactPersonslList(loginEmployee, idCompanyType);
			//构造_公司名称->联系人
			StringBuffer sb=new StringBuffer();
			for(int i=0;i<companiesList.size();i++){
				Map obj=(Map)companiesList.get(i);
				sb.append("<span id=\"cp"+obj.get("IDCOMPANY")+"\"><a href='JavaScript:showContact(\"c"+obj.get("IDCOMPANY")+"\");queryMail("+idCompanyType+","+obj.get("IDCOMPANY")+",\"\");'>&nbsp;&nbsp;&nbsp;&nbsp;").append(obj.get("COMPANYNAME")).append("</a><br></span>");
				for(int j=0;j<contactPersonsList.size();j++){
					Map obj2=(Map)contactPersonsList.get(j);
					if(obj.get("IDCOMPANY").equals(obj2.get("IDCOMPANY"))){
						sb.append("<span id=\"t"+obj2.get("IDCONTACTPERSON")+"\" class='c"+obj.get("IDCOMPANY")+"' style='display:none;'><a href='JavaScript:queryMail("+idCompanyType+","+obj2.get("IDCOMPANY")+","+obj2.get("IDCONTACTPERSON")+")'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;").append(obj2.get("FIRSTNAME")).append(obj2.get("LASTNAME")).append("</a><br></span>");
					}
				}
			}
			JsonUtil.stringPrintJson(request, response,sb.toString());
		}catch(Exception e){
			log.error("查询联系人失败，原因是："+e.getMessage(),e);
			JsonUtil.stringPrintJson(request, response, "false");
		}
		return null;
	}
	/******************************************************
	 ***********************辅助方法************************
	 ******************************************************/
	// 设置邮件基本信息
	private MailBean setMailBean(HttpServletRequest request,MailBean mailBean,TblMailDetail tblMailDetail,TblUserMail tblUserMail){
		// 附件
		String path = request.getSession().getServletContext().getRealPath("/")+ Constant.PATH;
		File file = new File(path);
		// 有附件
		if (file.exists() && file.isDirectory()) {
			//附件
			List<TblMailAnnex> mailAnnexList=this.tblMailAnnexService.getTblMailAnnexList(tblMailDetail.getIdMailAnnex(),1);
			List fileList=new ArrayList();
			StringBuffer fileNameBf = new StringBuffer();
			for(TblMailAnnex tblMailAnnex:mailAnnexList){
				fileNameBf.append(path).append(tblMailAnnex.getFilename()).append(",");
			}
			if (fileNameBf.length() > 0) {
				fileNameBf.deleteCharAt(fileNameBf.length() - 1);
				mailBean.setFileNames(fileNameBf.toString());// 将附件添加到附件列表中
			}
			//嵌入式文件
			Long key=System.currentTimeMillis();
			int count=mailBean.getContent().indexOf("src=\"");
			Map resFileMap=new HashMap();
			String msg="";
			while(true){
				if(count>-1){
					msg=mailBean.getContent().substring(count,mailBean.getContent().indexOf("\"", count+6));
					msg=msg.substring(msg.indexOf("\"")+1,msg.length());
					if(msg.indexOf("http://")==-1 && msg.indexOf(".")>-1){
						String imgType=msg.substring(msg.lastIndexOf("."),msg.length());
						mailBean.setContent(mailBean.getContent().replace(msg, "cid:"+key));
						//构造
						String realPath=request.getSession().getServletContext().getRealPath("/");
						msg=msg.replace(msg.substring(msg.indexOf("/"),msg.indexOf("/", msg.indexOf("/")+1)),"");
						msg=realPath+msg;
						resFileMap.put(key+imgType, msg);
						//重新定位count
						count=mailBean.getContent().indexOf("src=\"",count+6);
						if(count==-1)break;
						key++;
					}else{
						count=mailBean.getContent().indexOf("src=\"",count+6);
						if(count==-1)break;
					}
				}else{
					break;
				}
			}
			mailBean.setResources(resFileMap);
		}
		return mailBean;
	}
}
